﻿using System;
using System.Windows.Forms;
using Microsoft.Win32;
using Slippor.Douban.Radio.Assist;
using Slippor.Douban.Radio.BaseForm.Properties;
using Slippor.Douban.Radio.Filter;
using Slippor.Douban.Radio.Search;
using System.Threading;
using System.Globalization;

namespace Slippor.Douban.Radio.BaseForm
{
    public partial class DoubanForm 
    {
        #region Properties

        private readonly FilterCollection _filters = new FilterCollection();
        private readonly Settings _settings = StaticResources.Settings;

        private readonly ToolStripTracker _toolStripTracker = new ToolStripTracker();
        private bool _autoRun;

        public bool NotifyPop
        {
            get { return _settings.NotifyPop; }
            set
            {
                _settings.NotifyPop = value;
                _settings.Save();
            }
        }

        public bool RecordHistory
        {
            get { return _settings.RecordHistory; }
            set
            {
                if (_settings.RecordHistory != value)
                {
                    _settings.RecordHistory = value;
                    _settings.Save();
                    if (_settings.RecordHistory)
                    {
                        _trackerService.AddTracker(_toolStripTracker);
                        _toolStripTracker.Track(_currentSong);
                        AppendHistoryItem(_toolStripTracker.CurrentHistoryItem);
                    }
                    else
                    {
                        _trackerService.RemoveTracker(_toolStripTracker);
                    }
                }
            }
        }

        public bool AutoMin
        {
            get { return _settings.AutoMin; }
            set
            {
                if (_settings.AutoMin != value)
                {
                    _settings.AutoMin = value;
                    _settings.Save();
                }
            }
        }

        public bool EnableHotKey
        {
            get { return _settings.EnableHotkey; }
            set
            {
                if (_settings.EnableHotkey != value)
                {
                    _settings.EnableHotkey = value;
                    _settings.Save();
                }
            }
        }

        public bool GetInfo
        {
            get { return _settings.GetInfo; }
            set
            {
                if (_settings.GetInfo != value)
                {
                    _settings.GetInfo = value;
                    _settings.Save();
                }
            }
        }

        public bool AutoRun
        {
            get { return _autoRun; }
            set
            {
                if (_autoRun != value)
                {
                    _autoRun = value;
                    SetAutoRun(value);
                }
            }
        }

        public bool AutoUpdate
        {
            get { return _settings.AutoUpdate; }
            set
            {
                if (_settings.AutoUpdate != value)
                {
                    _settings.AutoUpdate = value;
                    _settings.Save();
                }
            }
        }

        public double FormOpacity
        {
            get { return _settings.FormOpacity; }
            set
            {
                _settings.FormOpacity = value;
                _settings.Save();
                Opacity = value;
            }
        }

        public bool FormTopMost
        {
            get { return _settings.OnTop; }
            set
            {
                if (_settings.OnTop != value)
                {
                    _settings.OnTop = value;
                    _settings.Save();
                }
                TopMost = value;
                if (TopMost)
                {
                    _dockTimer.Start();
                }
                else
                {
                    _dockTimer.Stop();
                    FormAutoDock.ResetDockForm(this);
                }
            }
        }

        public FilterCollection Filters
        {
            get { return _filters; }
        }

        public ISearch DefaultSearch
        {
            get
            {
                if (toolStripMenuItemSearch.DefaultSearch != null)
                {
                    return toolStripMenuItemSearch.DefaultSearch;
                }
                return new BaiduSearch();
            }
        }

        private void SetAutoRun(bool value)
        {
            String R_startPath = Application.ExecutablePath;
            try
            {
                using (RegistryKey R_local = Registry.LocalMachine)
                using (RegistryKey R_run = R_local.CreateSubKey(StaticResources.AutoRunPath))
                {
                    if (value)
                    {
                        if (R_run != null) R_run.SetValue("DoubanRadio", R_startPath);
                    }
                    else
                    {
                        if (R_run != null) R_run.DeleteValue("DoubanRadio", false);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(StringResource.Message_AdminRequire, StringResource.Message_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool IsTaskbarShow
        {
            get { return _settings.ShowTaskBar; }
            set
            {
                _settings.ShowTaskBar = value;
                _settings.Save();
                if(_currentState != RadioState.Notify)
                {
                    if(value)
                    {
                        ShowTaskBar();
                    }
                    else
                    {
                        HideTaskBar();
                    }
                }
            }
        }

        /// <summary>
        /// 当CloseOption = 0 的时候，关闭需要确认。 1 的时候，关闭；2 的时候，隐藏。
        /// </summary>
        public bool CloseConfirm
        {
            get { return _settings.CloseOption == 0; }
            set
            {
                if (value)
                {
                    _settings.CloseOption = 0;
                }
                else if (_settings.CloseOption == 0)
                {
                    _settings.CloseOption = 1;
                }
                _settings.Save();
            }
        }

        protected virtual void ShowTaskBar()
        {
            ShowInTaskbar = true;
        }

        protected virtual void HideTaskBar()
        {
            ShowInTaskbar = false;
        }

        public bool MenuOpen
        {
            get { return _settings.MenuOpen; }
            set
            {
                if(_settings.MenuOpen != value)
                {
                    _settings.MenuOpen = value;
                    _settings.Save();
                }
            }
        }

        public bool BottomMenuOpen
        {
            get { return _settings.BottomMenuOpen; }
            set
            {
                if (_settings.BottomMenuOpen != value)
                {
                    _settings.BottomMenuOpen = value;
                    _settings.Save();
                }
            }
        }

        public String Language
        {
            get { return _settings.Language; }
            set
            {
                if (_settings.Language != value)
                {
                    _settings.Language = value;
                    _settings.Save();
                    if (value != "Auto")
                    {
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo(value);
                    }
                    else
                    {
                        Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture;
                    }
                    RefreshLanguages();
                }
            }
        }

        public String ProxyAddress
        {
            get { return _settings.ProxyAddress; }
            set
            {
                if (_settings.ProxyAddress != value)
                {
                    _settings.ProxyAddress = value;
                }
            }
        }

        public String ProxyPort
        {
            get { return _settings.ProxyPort; }
            set
            {
                if (_settings.ProxyPort != value)
                {
                    _settings.ProxyPort = value;
                }
            }
        }

        public bool UseProxy
        {
            get { return _settings.UseProxy; }
            set 
            {
                if (_settings.UseProxy != value)
                {
                    _settings.UseProxy = value;
                    CheckProxy();
                    _axBrowser.Refresh();
                }
            }
        }

        private void CheckProxy()
        {
            if (UseProxy)
            {
                String proxy = String.Empty;
                if (ProxyAddress != String.Empty)
                {
                    proxy = String.Format("http://{0}:{1}", ProxyAddress, ProxyPort);
                }
                RadioUtility.RefreshIESettings(proxy);
                DoubanWebWorker.Proxy = proxy;
            }
            else
            {
                String proxy = String.Empty;
                RadioUtility.RefreshIESettings(proxy);
                DoubanWebWorker.Proxy = proxy;
            }
        }

        private void RefreshLanguages()
        {
            if (_currentSong == null)
            {
                this.Text = StringResource.Title;
                this.notifyIcon.Text = StringResource.Title;
                this.toolStripMenuItemTitle.Text = StringResource.Title;
            }
            else
            {
                this.toolStripMenuItemGetInfo.Text = StringResource.D_toolStripMenuItemGetInfo;
            }
            if (!_currentAccount.IsLoged)
            {
                this.loginToolStripMenuItem.Text = StringResource.Loggin;
            }
            this.toolStripMenuItemTitle.ToolTipText = StringResource.ClickToCopy;
            this.toolStripMenuItemMostTop.Text = StringResource.D_toolStripMenuItemMostTop;
            this.toolStripMenuItemPop.Text = StringResource.D_toolStripMenuItemPop;
            this.toolStripMenuItemAdvance.Text = StringResource.D_toolStripMenuItemAdvance;
            this.toolStripMenuItemHistory.Text = StringResource.D_toolStripMenuItemHistory;
            this.toolStripMenuItemClear.Text = StringResource.D_toolStripMenuItemClear;
            this.toolStripMenuItemShow.Text = StringResource.D_toolStripMenuItemShow;
            this.toolStripMenuItemRefresh.Text = StringResource.D_toolStripMenuItemRefresh;
            this.toolStripMenuItemLogin.Text = StringResource.D_toolStripMenuItemLogin;
            this.toolStripMenuItemRestart.Text = StringResource.D_toolStripMenuItemRestart;
            this.toolStripMenuItemClose.Text = StringResource.D_toolStripMenuItemClose;
            this.labelLoading.Text = StringResource.Loading;
            this.toolStripMenuItemPlugins.Text = StringResource.PluginManager;
            this.toolTipMain.SetToolTip(this.pictureBoxMenu, StringResource.D_pictureBoxMenu_TT);
            this.dockPanel.DockText = StringResource.Title;
            this.ShareToolStripMenuItem.Text = StringResource.D_ShareToolStripMenuItem;
            _loginForm.RefreshLanguage();
        }

        protected virtual void InitialProperties()
        {
            _settings.Upgrade();

            SuspendLayout();
            Language = Language;

            toolStripMenuItemPop.Checked = NotifyPop;
            FormTopMost = toolStripMenuItemMostTop.Checked = FormTopMost;
            ShowInTaskbar = IsTaskbarShow;
            toolStripMenuItemSearch.SetDefault(_settings.DefaultSearch);
            Opacity = FormOpacity;
            ResumeLayout();

            try
            {
                using (RegistryKey R_local = Registry.LocalMachine)
                using (RegistryKey R_run = R_local.CreateSubKey(StaticResources.AutoRunPath))
                {
                    if (R_run != null)
                        _autoRun = R_run.GetValue("DoubanRadio") != null &&
                                   (R_run.GetValue("DoubanRadio").ToString() == Application.ExecutablePath);
                }
            }
            catch
            {
                ;
            }
            CheckFilters(_settings.Filters);
            if (AutoUpdate)
            {
                VersionControl.CheckVersion(_currentVersion, VersionCheckEnd);
            }
            if (RecordHistory)
            {
                _trackerService.AddTracker(_toolStripTracker);
            }
            ShowTopMenu(MenuOpen);
            ShowBottomMenu(BottomMenuOpen);
            CheckProxy();
        }

        protected internal virtual void OnResetting()
        {
            toolStripMenuItemPop.Checked = NotifyPop;
            FormTopMost = toolStripMenuItemMostTop.Checked = FormTopMost;
            Opacity = FormOpacity;
            CheckFilters(_settings.Filters);
        }

        private void CheckFilters(String filters)
        {
            if (!String.IsNullOrEmpty(filters))
            {
                String[] filterArray = filters.Split(',');
                lock (_filters.ForLock)
                {
                    foreach (String filter in filterArray)
                    {
                        if (!String.IsNullOrEmpty(filter))
                        {
                            IFilter iFilter;
                            switch (filter)
                            {
                                case EnglishFilter.Key:
                                    iFilter = new EnglishFilter();
                                    break;
                                case ChineseFilter.Key:
                                    iFilter = new ChineseFilter();
                                    break;
                                default:
                                    iFilter = new CustomFilter(filter);
                                    break;
                            }
                            _filters[filter] = iFilter;
                        }
                    }
                }
            }
        }
        #endregion
    }
}
